package com.heima.admin.config;

import com.heima.admin.service.AdUserLogService;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.pojos.AdUserLog;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.pojos.WmUser;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;


/**
 * @author Promise
 * @createTime 2018年12月18日 下午9:33:28
 * @description 切面日志配置
 */
@Aspect
@Component
public class LogAsPect {
    private final static Logger log = org.slf4j.LoggerFactory.getLogger(LogAsPect.class);

    @Autowired
    private AdUserLogService adUserLogService;

    @Autowired
    private AdUserService adUserService;

    @Autowired
    private WemediaFeign wemediaFeign;

    @Autowired
    private UserFeign userFeign;

    //表示匹配带有自定义注解的方法
    @Pointcut("@annotation(com.heima.admin.config.Log)")
    public void pointcut() {
    }

    /**
     * 定义环绕通知，实现查询时长的统计
     * 要求：log4j统计方法的运行时间，运行参数，执行时长，哪个方法运行的
     *
     * @return
     */
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) {
        AdUserLog sys_log = new AdUserLog();
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String uri = request.getRequestURI();
        String httpMethod = request.getMethod();
        String ip = request.getRemoteAddr();
        String classMethod =
                point.getSignature().getDeclaringTypeName() + "." + point.getSignature().getName();
        String args = Arrays.toString(point.getArgs());

        sys_log.setRequestPath(uri);
        sys_log.setRequestMethod(httpMethod);
        sys_log.setRemoteddr(ip);
        sys_log.setMethodName(classMethod);

        // 记录下请求内容
        log.info("URL : " + request.getRequestURL().toString());
        log.info("HTTP_METHOD : " + request.getMethod());
        log.info("IP : " + request.getRemoteAddr());
        log.info("CLASS_METHOD : " + point.getSignature().getDeclaringTypeName() + "." + point.getSignature().getName());
        log.info("ARGS : " + Arrays.toString(point.getArgs()));

        Object result = null;
        try {
            //统计时长---开始时间
            long beginTime = System.currentTimeMillis();
            log.info("我在目标方法之前执行！");
            result = point.proceed();

            String userId = request.getHeader("userId");
            AdUser adUser = adUserService.getById(userId);
            if (adUser == null){
                return result;
            }
            String name = adUser.getName();
            sys_log.setOperation(name);
            sys_log.setOperationId(userId);
            long endTime = System.currentTimeMillis();
            sys_log.setExecuteTime(endTime - beginTime);
            insertLog(point, sys_log);
        } catch (Throwable throwable) {
            // TODO Auto-generated catch block
            throwable.printStackTrace();
        }
        return result;
    }

    private void insertLog(ProceedingJoinPoint point, AdUserLog sys_log) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Log userAction = method.getAnnotation(Log.class);
        if (userAction != null) {
            // 注解上的描述
            sys_log.setRequestOperation(userAction.value());
        }
        // 请求的类名
//        String className = point.getTarget().getClass().getName();
        // 请求的方法名
//        String methodName = signature.getName();
//        sys_log.setMethod(className + "." + methodName + "()");
        // 请求的方法参数值
//        String args = Arrays.toString(point.getArgs());

        //从session中获取当前登陆人id //      Long useride = (Long)SecurityUtils.getSubject().getSession().getAttribute("userid");

        sys_log.setCreatedTime(new java.sql.Timestamp(new Date().getTime()));

//        log.info("当前登陆人：{},类名:{},方法名:{},参数：{},执行时间：{}", userid, className, methodName, args, time);

        adUserLogService.insertLog(sys_log);
    }

}
